rm(list=ls())

library(ggplot2)
library(RColorBrewer)

#set working directory:
setwd() #set to your local working directory

#load data:
orgs <- read.csv('2015_PR_MORENA_orgs.csv', header=T, sep=",")

#subset to elected deputies (data is only available for them):
orgs <- subset(orgs, diputado_dummy==1)

#randomized deputies:
orgs_internal <- subset(orgs, internal==1)

summary(orgs_internal$org_involvement)

#distributions of organizational involvement:
org_dist <- as.data.frame(xtabs(~ orgs_internal$org_type))
org_dist[,1] <- as.character(org_dist[,1])
org_dist[1,1] <- "None"
names(org_dist)[1] <- "Type"
org_dist$Type[org_dist$Type=="labor"] <- "Labor Union"
org_dist$Type[org_dist$Type=="peasant"] <- "Peasant Union"
org_dist$Type[org_dist$Type=="professional"] <- "Professional Association"
org_dist$Type[org_dist$Type=="student"] <- "Student Union"
org_dist$Type[org_dist$Type=="women"] <- "Women's Association"
org_dist$Type <- as.factor(org_dist$Type)

org_dist$Share <- org_dist$Freq/sum(org_dist$Freq)
org_dist$Party <- "MORENA"
org_dist

org_dist$Type <- factor(org_dist$Type,levels = c("None","Student Union","Women's Association","Professional Association","Peasant Union","Labor Union"))

#to create a color palette with enough colors for all categories:
colourCount = length(unique(org_dist$Type))
getPalette = colorRampPalette(brewer.pal(12, "Paired"))

org_involvement_fig <- ggplot(data = org_dist , aes(x = Party, y = Share*100, fill = Type)) +
  geom_bar(position = "stack", stat = "identity", width = .5) +
  theme_minimal() + 
  theme(legend.position = "bottom") +
  theme(legend.text=element_text(size=11)) + 
  theme(axis.text = element_text(size = 11))  +
  labs(title=" ")  + 
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())+
xlab("") + ylab("Proportion (%)") + 
  coord_flip() +
  labs(fill = " ") +
  scale_fill_manual(values=c("#F6F7EB","#70F8BA","#FFC857","#DB3A34","#084C61","#177E89")) +
      guides(fill = guide_legend(reverse = TRUE)) 

org_involvement_fig
#Figure 4:
ggsave("fg4.pdf", width = 10, height = 2.5, units = "in")

